import React, { Component } from 'react';
import {
  View,
  FlatList,
  StyleSheet,
  DeviceEventEmitter,
} from 'react-native';
import {
  BlankBackground,
  ListFooter,
} from '../components';
import PushItem from '../components/pushItem';
import ZlstIcon from '../components/zlst-icons';
import Theme from '../native-base-theme/variables/commonColor';
import ReportForm from '../components/reportForm';
import * as messageService from '../services/message';

class PushList extends Component {
  static navigationOptions = {
    title: '消息',
    headerStyle: { backgroundColor: Theme.toolbarDefaultBg },
    headerTintColor: '#FFFFFF',
    headerTitleStyle: {
      fontWeight: 'bold',
      fontSize: 20,
      flex: 1,
      textAlign: 'center',
    },
    headerBackImage: (
      <ZlstIcon
        name="fanhui"
        size={24}
        color="white"
      />
    ),
    headerRight: <View />,
  }

  currentPage = 1;

  constructor(props) {
    super(props);
    this.state = {
      refreshing: false,
      isError: false,
      listData: [],
      showReportForm: false,
      isMore: false,
      reportUri: '',
    };
  }

  componentDidMount() {
    this.fetchData();
  }

  componentWillUnmount() {
    DeviceEventEmitter.emit('refreshBadgeEvent');
  }

  fetchData = async () => {
    try {
      // DeviceEventEmitter.emit('showLoading', true);
      const userCode = global.user.name;
      const resp = await messageService.search({ page: this.currentPage, userCode });
      // DeviceEventEmitter.emit('showLoading', false);
      this.setState(preState => {
        const listData = preState.listData.concat(resp.list);
        return ({
          listData,
          isMore: listData.length < resp.total,
        });
      });
      this.msgRead(resp.list.map(item => item._id));
    } catch (error) {
      // DeviceEventEmitter.emit('showLoading', false);
      console.log('error...', error);
    }
  }

  // 将请求的数据变成已读
  msgRead = (ids) => {
    // const idsStr = ids.join(',');
    messageService.msgReadBatch(ids);
  }

  // 列表上拉加载没有数据时
  _renderListFooter = () => (
    (this.state.listData.length > 0) && <ListFooter isMore={this.state.isMore} />
  )

  _onEndReached = () => {
    console.log('endReached!');
    if (this.state.isMore) {
      this.currentPage += 1;
      this.fetchData();
    }
  }

  _renderRow = (item) => <PushItem item={item.item} openWebView={this.openWebView} />

  _onRefresh = () => {
    this.state.listData = [];
    this.currentPage = 1;
    this.fetchData();
  }

  _getListContent = () => {
    const { listData, refreshing, isError } = this.state;
    if (listData && !listData.length) {
      return (
        <BlankBackground isError={isError} onRefresh={this._onRefresh} />
      );
    }
    return (
      <FlatList
        showsVerticalScrollIndicator={false}
        data={listData}
        renderItem={item => this._renderRow(item)}
        keyExtractor={(item, index) => `${item + index}`}
        onRefresh={this._onRefresh}
        refreshing={refreshing}
        onEndReachedThreshold={0.3}
        scrollEventThrottle={200}
        onEndReached={this._onEndReached}
        ListFooterComponent={this._renderListFooter}
      />
    );
  }

  openWebView = (reportUri) => {
    console.log('openWebView');
    this.setState({
      showReportForm: true,
      reportUri,
    });
  }

  closeWebView = () => {
    console.log('closeWebView');
    this.setState({
      showReportForm: false,
    });
  }

  render() {
    return (
      <View style={styles.container}>
        {
          this.state.showReportForm && (
            <ReportForm
              show={this.state.showReportForm}
              hide={this.closeWebView}
              uri={this.state.reportUri}
            />
          )
        }
        {this._getListContent()}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: '100%',
    height: '100%',
    backgroundColor: Theme.myPrimary,
  },
});

export default PushList;
